<?php
//顶层异常处理器
function myException($e){
	exit('出错:'.$e->getMessage());
}
set_exception_handler('myException');
//支付宝接口类
class AlipayService
{
	//配置
	private $appId; //应用ID
	private $rsaPrivateKey; //商户私钥，填写对应签名算法类型的私钥，如何生成密钥参考：https://docs.open.alipay.com/291/105971和https://docs.open.alipay.com/200/105310
	private $alipayPublicKey; //支付宝公匙
	private $gatewayUrl; //请求的网关地址
	//
	private $apiMethodName; //请求的接口名称
	private $apiVersion = '1.0'; //请求的接口版本，固定为：1.0
	private $charset = 'utf-8'; //请求的编码格式
	private $signType = "RSA2"; //商户生成签名字符串所使用的签名算法类型
	private $format = "JSON"; //响应的格式
	private $SIGN_NODE_NAME = 'sign'; //响应的签名标识
	private $RESPONSE_SUFFIX = '_response'; //响应的根节点标识的后缀
	private $ERROR_RESPONSE = 'error_response'; //响应的错误标识节点
	
    public function __construct($appId,$rsaPrivateKey,$alipayPublicKey,$gatewayUrl)
    {
		$this->appId=$appId;
		$this->rsaPrivateKey=$rsaPrivateKey;
		$this->alipayPublicKey=$alipayPublicKey;
		$this->gatewayUrl=$gatewayUrl;   		
    }
    /**
     * 发起请求
     * @return object
     */
    public function doRequest($requestConfigs,$commonConfigsMore=array())
    { 
		//公共参数
		$commonConfigs = array(
			'app_id' => $this->appId,
			'format' => $this->format,
			'charset'=>$this->charset,
			'sign_type'=>$this->signType,
			'timestamp'=>date('Y-m-d H:i:s'), //发送请求的时间，格式"yyyy-MM-dd HH:mm:ss"
			'version'=>$this->apiVersion,
			'biz_content'=>json_encode($requestConfigs) //请求参数的集合，最大长度不限，除公共参数外所有请求参数都必须放在这个参数中传递
		);
		//附加额外公共参数
		if(!empty($commonConfigsMore)){
			$commonConfigs = array_merge($commonConfigs,$commonConfigsMore);
		}
		$this->apiMethodName = $commonConfigs['method'];
        $commonConfigs["sign"] = $this->generateSign($commonConfigs, $this->signType);//生成签名
		$resp = $this->curlPost($this->gatewayUrl,$commonConfigs);//发起请求
		//$resp = iconv('GBK', $this->charset . "//IGNORE", $resp);//转码
		//echo $resp;
		//$resp=str_replace('order_id','order_id1',$resp);
		$respObject = json_decode($resp);//转json对象
		$this->checkResponseSign($resp, $respObject);//验证响应签名
		//
		$rootNodeName = str_replace(".", "_", $this->apiMethodName) . $this->RESPONSE_SUFFIX;//获取响应的根节点名称
		return $respObject->$rootNodeName;//json_decode($resp,true);
    }
	/**
     * 签名
     */
    private function generateSign($params, $signType = "RSA") {
        return $this->sign($this->getSignContent($params), $signType);
    }
	/**
     * openssl签名
     */
    private function sign($data, $signType = "RSA") {
        $priKey=$this->rsaPrivateKey;
        $res = "-----BEGIN RSA PRIVATE KEY-----\n" .
            wordwrap($priKey, 64, "\n", true) .
            "\n-----END RSA PRIVATE KEY-----";
        ($res) or die('您使用的私钥格式错误，请检查RSA私钥配置');
        if ("RSA2" == $signType) {
            openssl_sign($data, $sign, $res, version_compare(PHP_VERSION,'5.4.0', '<') ? SHA256 : OPENSSL_ALGO_SHA256); //OPENSSL_ALGO_SHA256是php5.4.8以上版本才支持
        } else {
            openssl_sign($data, $sign, $res);
        }
        $sign = base64_encode($sign);
        return $sign;
    }	
	/**
     * 将数组组合成字符串&连接(去掉空值)
     **/
    private function getSignContent($params) {
        ksort($params);
        $stringToBeSigned = "";
        $i = 0;
        foreach ($params as $k => $v) {
            if (false === $this->checkEmpty($v) && "@" != substr($v, 0, 1)) {
                // 转换成目标字符集
                $v = $this->characet($v, $this->charset);
                if ($i == 0) {
                    $stringToBeSigned .= "$k" . "=" . "$v";
                } else {
                    $stringToBeSigned .= "&" . "$k" . "=" . "$v";
                }
                $i++;
            }
        }
        unset ($k, $v);
        return $stringToBeSigned;
    }
	/**
     * 校验$value是否非空
     *  if not set ,return true;
     *    if is null , return true;
     **/
    private function checkEmpty($value) {
        if (!isset($value))
            return true;
        if ($value === null)
            return true;
        if (trim($value) === "")
            return true;
        return false;
    }
    /**
     * 转换字符集编码
     * @param $data
     * @param $targetCharset
     * @return string
     */
    private function characet($data, $targetCharset) {
        if (!empty($data)) {
            $fileType = $this->charset;
            if (strcasecmp($fileType, $targetCharset) != 0) {//二进制不相等
                $data = mb_convert_encoding($data, $targetCharset, $fileType);
                //$data = iconv($fileType, $targetCharset.'//IGNORE', $data);
            }
        }
        return $data;
    }
	/**
     * Curl
     */
    private function curlPost($url = '', $postData = array(), $options = array())
    {  
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
		if (!empty($postData)) {
			curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
        }
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }
        //https请求 不验证证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('content-type: application/x-www-form-urlencoded;charset=' . $this->charset));
        $data = curl_exec($ch);
		if (curl_errno($ch)) {
			throw new Exception('curl-'.curl_error($ch));
		} else {
			$httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
			if (200 !== $httpStatusCode) {
				throw new Exception('响应HTTP状态码'.$httpStatusCode);
			}
		}
        curl_close($ch);
        return $data;
    }
	/**
	 * 回调(同步/异步)验证签名
	 **/
	public function rsaCheck($params) {
		$sign = $params['sign'];
		$signType = $params['sign_type'];
		unset($params['sign_type']);
		unset($params['sign']);
		return $this->verify($this->getSignContent($params), $sign, $signType);
	}
	/**
     * openssl验证签名
     */
	private function verify($data, $sign, $signType = 'RSA') {
		$pubKey= $this->alipayPublicKey;
		$res = "-----BEGIN PUBLIC KEY-----\n" .
		    wordwrap($pubKey, 64, "\n", true) .
		    "\n-----END PUBLIC KEY-----";
		($res) or die('支付宝RSA公钥错误。请检查公钥文件格式是否正确');
		//调用openssl内置方法验签，返回bool值
		if ("RSA2" == $signType) {
		    $result = (bool)openssl_verify($data, base64_decode($sign), $res, version_compare(PHP_VERSION,'5.4.0', '<') ? SHA256 : OPENSSL_ALGO_SHA256);
		} else {
		    $result = (bool)openssl_verify($data, base64_decode($sign), $res);
		}
		//if(!$this->checkEmpty($this->alipayPublicKey)) {
			//释放资源
			//openssl_free_key($res);
		//}
		return $result;
	}
	/**
     * 响应签名验证
     */
	private function checkResponseSign($resp, $respObject) {
		$signData = $respObject->sign;
		$signDataSource = $this->parserJSONSignSource($resp);
		if (!$this->checkEmpty($this->alipayPublicKey)) {
			if ($this->checkEmpty($signData) || $this->checkEmpty($signDataSource)) {
				throw new Exception('响应签名为空');
			}
			// 获取结果sub_code
			$responseSubCode = $this->parserResponseSubCode($resp, $respObject, $this->format);
			if (!$this->checkEmpty($responseSubCode) || ($this->checkEmpty($responseSubCode) && !$this->checkEmpty($signData))) {
				$checkResult = $this->verify($signDataSource, $signData, $this->signType);
				if (!$checkResult) {
					if (strpos($signDataSource, "\\/") > 0) {
						$signDataSource = str_replace("\\/", "/", $signDataSource);
						$checkResult = $this->verify($signDataSource, $signData, $this->signType);
						if (!$checkResult) {
							throw new Exception('响应签名验证不通过');
						}
					} else {
						throw new Exception('响应签名验证不通过');
					}
				}
			}
		}
	}
	private function parserJSONSignSource($responseContent) {
		$apiName = $this->apiMethodName;
		$rootNodeName = str_replace(".", "_", $apiName) . $this->RESPONSE_SUFFIX;
		$rootIndex = strpos($responseContent, $rootNodeName);
		$errorIndex = strpos($responseContent, $this->ERROR_RESPONSE);
		if ($rootIndex > 0) {
			return $this->parserJSONSource($responseContent, $rootNodeName, $rootIndex);
		} else if ($errorIndex > 0) {
			return $this->parserJSONSource($responseContent, $this->ERROR_RESPONSE, $errorIndex);
		} else {
			return null;
		}
	}
	private function parserJSONSource($responseContent, $nodeName, $nodeIndex) {
		$signDataStartIndex = $nodeIndex + strlen($nodeName) + 2;
		$signIndex = strpos($responseContent, "\"" . $this->SIGN_NODE_NAME . "\"");
		// 签名前-逗号
		$signDataEndIndex = $signIndex - 1;
		$indexLen = $signDataEndIndex - $signDataStartIndex;
		if ($indexLen < 0) {
			return null;
		}
		return substr($responseContent, $signDataStartIndex, $indexLen);
	}
	//获取业务返回码sub_code
	private function parserResponseSubCode($responseContent, $respObject, $format) {
		if ("json" == $format) {
			$apiName = $this->apiMethodName;
			$rootNodeName = str_replace(".", "_", $apiName) . $this->RESPONSE_SUFFIX;
			$errorNodeName = $this->ERROR_RESPONSE;
			$rootIndex = strpos($responseContent, $rootNodeName);
			$errorIndex = strpos($responseContent, $errorNodeName);
			if ($rootIndex > 0) {
				// 内部节点对象
				$rInnerObject = $respObject->$rootNodeName;
			} elseif ($errorIndex > 0) {
				$rInnerObject = $respObject->$errorNodeName;
			} else {
				return null;
			}
			// 存在属性则返回对应值
			if (isset($rInnerObject->sub_code)) {
				return $rInnerObject->sub_code;
			} else {
				return null;
			}
		} elseif ("xml" == $format) {
			// xml格式sub_code在同一层级
			return $respObject->sub_code;
		}
	}
}